import 'dart:io';

import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/common/model/upload_result_entity.dart';
import 'package:tender_flutter/page/person/api/api_person.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/img_picker.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';

class FeedbackPage extends StatefulWidget {
  @override
  _FeedbackPageState createState() => _FeedbackPageState();
}

class _FeedbackPageState extends State<FeedbackPage> {
  /// 默认最大选择的图片数量
  int maxNum = 3;

  /// 选择的图片文件
  List<File> _selectImageFile = [];

  /// 上传完成的图片urls
  List<String> _imageUrls = [];

  /// 输入内容
  String _content = "";

  /// 提交反馈
  Future _sbumitFeedback() async {
    if (_content.isEmpty) {
      ToastUtils.show("请输入反馈内容");
      return;
    }

    /// 上传图片
    List<Future> uploadApis = _selectImageFile
        .map((e) => _uploadImage(e).then((value) => _imageUrls.add(value.url)))
        .toList();

    Future.wait(uploadApis).then((value) {
      _submitFormDatas().then((sValue) {
        if (sValue.status == Status.SUCCESS) {
          ToastUtils.show("反馈成功");
          LRouter.navigatorCtx(context).pop();
        }
      });
    }).catchError((e) {
      print(e.toString());
      ToastUtils.show("图片资源处理失败");
    });
  }

  /// 提交表单数据
  Future _submitFormDatas() {
    return ApiPerson.feedback(content: _content, pics: _imageUrls);
  }

  /// 上传图片
  Future _uploadImage(File file) async {
    ApiResponse<UploadResultEntity> response =
        await ApiCommon.uploadImage([file]);
    return response.result;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _initBody(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("意见反馈", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 内容体
  Widget _initBody() {
    return SingleChildScrollView(
        child: Stack(children: [
      Container(
          margin: EdgeInsets.all(ScreenAdapter.width(30)),
          child: Column(children: [
            Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    // height: ScreenAdapter.height(350),
                    padding: EdgeInsets.all(ScreenAdapter.width(30)),
                    decoration: BoxDecoration(
                        color: ThemeColors.colorWhite,
                        border: new Border.all(
                            width: 1, color: ThemeColors.colorType39),
                        borderRadius:
                            BorderRadius.circular(ScreenAdapter.width(10))),
                    child: TextField(
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.zero,
                          hintText: "请留下您宝贵的意见和建议，我们将努力改进（不少于5个字)",
                          border: InputBorder.none),
                      style: TextStyle(
                        color: ThemeColors.colorType4,
                        fontSize: ScreenAdapter.sp(30),
                      ),
                      // validator: (val) {
                      //   return val.length <= 0 ? placeholder : null;
                      // },
                      // onChanged: onChangeCallback,
                      // onSaved: onSaveCallback,
                      textAlign: TextAlign.left,
                      maxLength: 100,
                      maxLines: 5,
                      autofocus: false,
                      onChanged: (value) {
                        _content = value;
                      },
                    ),
                  ),
                  SizedBox(height: ScreenAdapter.height(28)),
                  Text("问题截图（可选）",
                      style: TextStyle(
                          color: ThemeColors.colorType14,
                          fontSize: ScreenAdapter.sp(30))),
                  SizedBox(height: ScreenAdapter.height(28)),
                  _initImagesList()
                ]),
            _initSubmitBtn()
          ]))
    ]));
  }

  /// 添加的图片列表
  Widget _initImagesList() {
    return GridView.builder(
        itemCount: _selectImageFile.length + 1,
        //SliverGridDelegateWithFixedCrossAxisCount 构建一个横轴固定数量Widget
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            //横轴元素个数
            crossAxisCount: 3,
            //纵轴间距
            mainAxisSpacing: ScreenAdapter.height(30),
            //横轴间距
            crossAxisSpacing: ScreenAdapter.width(20),
            //子组件宽高长度比例
            childAspectRatio: 1.0),
        itemBuilder: (BuildContext context, int index) {
          bool isAdd = index < _selectImageFile.length ? false : true;
          File file =
              index < _selectImageFile.length ? _selectImageFile[index] : null;
          return _getPicturesItem(
              file: file,
              isAdd: isAdd,
              clickCallback: () {
                if (_selectImageFile.length >= maxNum) {
                  ToastUtils.show("您选择的图片数量已达到最大限制");
                } else {
                  ImagePickerUtils.getImage(PICKER_PHOTO).then((value) {
                    if (value != null) {
                      setState(() {
                        _selectImageFile.add(value);
                      });
                    }
                  });
                }
              },
              deleteCallback: () {
                setState(() {
                  _selectImageFile.removeAt(index);
                });
              });
        });
  }

  /// 提交按钮
  Widget _initSubmitBtn() {
    return Container(
        height: ScreenAdapter.height(90),
        width: double.infinity,
        margin: EdgeInsets.symmetric(
            vertical: ScreenAdapter.height(75),
            horizontal: ScreenAdapter.width(30)),
        decoration: BoxDecoration(
            color: ThemeColors.colorType6,
            borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
        child: FlatButton(
            onPressed: () {
              _sbumitFeedback();
            },
            child: Text("提交",
                style: TextStyle(
                    color: ThemeColors.colorWhite,
                    fontSize: ScreenAdapter.sp(32)))));
  }

  /// 图片Item
  Widget _getPicturesItem(
      {File file,
      bool isAdd,
      VoidCallback clickCallback,
      VoidCallback deleteCallback}) {
    return Stack(
      children: <Widget>[
        GestureDetector(
          onTap: isAdd ? clickCallback : null,
          child: Container(
              width: double.infinity,
              height: double.infinity,
              margin: EdgeInsets.symmetric(
                  vertical: ScreenAdapter.height(10),
                  horizontal: ScreenAdapter.width(10)),
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(ScreenAdapter.width(12)),
                  child: isAdd
                      ? Image.asset(
                          RPath.imgPath + "img_add_placeholder.png",
                          fit: BoxFit.fill,
                        )
                      : Image.file(file, fit: BoxFit.cover))),
        ),
        !isAdd
            ? Positioned(
                right: 0,
                top: 0,
                child: GestureDetector(
                  onTap: deleteCallback,
                  child: Container(
                      child: Image.asset(RPath.imgPath + "icon_close_x.png",
                          width: ScreenAdapter.width(20),
                          height: ScreenAdapter.width(20))),
                ),
              )
            : Container()
      ],
    );
  }
}
